package com.wssnail.oss.config;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.wssnail.oss.properties.QiNiuConfig;
import com.wssnail.oss.template.OssTemplate;
import com.wssnail.oss.template.QiNiuOssTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: 七牛云自动装配类
 * @CreateTime: 2022-07-11 14:26
 * @Description: TODO
 * @Version: 1.0
 */
@Configuration
@EnableConfigurationProperties(QiNiuConfig.class)
public class SnailOssAutoConfig {

    @Autowired
    private QiNiuConfig qiNiuConfig;


    @Bean
    @ConditionalOnMissingBean
    Auth auth() {
        return Auth.create(qiNiuConfig.getAccessKey(), qiNiuConfig.getSecretKey());
    }

    @Bean("qiniuConfiguration")
    @ConditionalOnMissingBean
    public com.qiniu.storage.Configuration qiniuConfiguration() {
        com.qiniu.storage.Configuration configuration = new com.qiniu.storage.Configuration(Zone.autoZone());
        //防止上传发生401错误
        configuration.useHttpsDomains = false;
        return configuration;
    }

    @Bean("uploadManager")
    @ConditionalOnMissingBean
    public UploadManager uploadManager() {
        return new UploadManager(qiniuConfiguration());
    }

    @Bean("bucketManager")
    @ConditionalOnMissingBean
    BucketManager BucketManager() {
        return new BucketManager(auth(), qiniuConfiguration());
    }

    @Bean("qiNiuFileTemplate")
    @ConditionalOnMissingBean
    public OssTemplate qiNiuFileTemplate() {
        return new QiNiuOssTemplate(qiNiuConfig.getBucketName(),
                qiNiuConfig.getTempPath(), qiNiuConfig.getDomain(), auth(), BucketManager(), uploadManager(),qiNiuConfig.getBlockSize(),qiNiuConfig.getUrlPrefix());
    }

}
